<script setup lang="ts">
import { defineProps, PropType, ref, watch } from 'vue';
import { useBooleanStore } from '@/store';
import { Notification } from '@arco-design/web-vue';
import { getName } from '@/utils/auth';
import dayjs from 'dayjs';
import { getStocktakingDelete, getStocktakingDetail } from '@/api/stocktaking';
import { LocationTypeOption } from '@/api/les/types';
import { TableDataResponse } from '@/api/stocktaking/types';

const props = defineProps<{
  tableData: TableDataResponse | null;
  stocktakingTypeOptions: LocationTypeOption[];
  statusOptions: LocationTypeOption[];
  trayOptions: LocationTypeOption[];
  largeLocationOptions: any[];
}>();

const columns: any[] = [
  {
    title: '盘点任务',
    align: 'left',
    headerCellStyle: { fontSize: 'medium', fontWeight: 400 },
    children: [
      {
        title: '序号',
        dataIndex: 'index',
        slotName: 'index',
        align: 'center',
      },
      {
        title: '盘点单号',
        dataIndex: 'code',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '盘点类型',
        dataIndex: 'type',
        slotName: 'type',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '盘点状态',
        dataIndex: 'status',
        slotName: 'status',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '是否大件',
        dataIndex: 'isLarge',
        slotName: 'isLarge',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '计划日期',
        dataIndex: 'planDate',
        slotName: 'planDate',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '要求完成日期',
        dataIndex: 'finishedDate',
        slotName: 'finishedDate',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '托盘/箱号',
        dataIndex: 'trayCode',
        slotName: 'trayCode',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '大件库位',
        dataIndex: 'locationCode',
        slotName: 'locationCode',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '大件物料',
        dataIndex: 'materialCode',
        slotName: 'materialCode',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '抽盘比例(%)',
        dataIndex: 'ratio',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '创建人',
        dataIndex: 'createUser',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '修改人',
        dataIndex: 'updateUser',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '修改时间',
        dataIndex: 'updateTime',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '备注',
        dataIndex: 'remarks',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '操作',
        dataIndex: 'action',
        slotName: 'action',
        align: 'center',
        fixed: 'right',
      },
    ],
  },
];

const detailColumns: any[] = [
  {
    title: '盘点记录',
    align: 'left',
    headerCellStyle: { fontSize: 'large', fontWeight: 400 },
    children: [
      {
        title: '序号',
        dataIndex: 'index',
        slotName: 'index',
        align: 'center',
        width: 60,
      },
      {
        title: 'AO编码',
        dataIndex: 'aoCode',
        width: 140,
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '物料名称',
        dataIndex: 'materialName',
        width: 140,
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '物料编码',
        dataIndex: 'materialCode',
        width: 140,
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '物料图号',
        width: 140,
        dataIndex: 'materialDrawingNo',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '物料型号',
        width: 140,
        dataIndex: 'materialModelNo',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '物料规格',
        width: 140,
        dataIndex: 'materialSpecifications',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '库存数量',
        dataIndex: 'inventoryQty',
        width: 100,
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '托盘编码',
        width: 140,
        dataIndex: 'palletCode',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '库存日期',
        width: 100,
        dataIndex: 'inventoryDate',
        slotName: 'inventoryDate',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '库位编码',
        width: 120,
        dataIndex: 'locationCode',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '盘点数量',
        width: 100,
        dataIndex: 'qty',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '盘点人',
        width: 100,
        dataIndex: 'createUser',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '盘点时间',
        width: 160,
        dataIndex: 'createTime',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '备注',
        width: 140,
        dataIndex: 'remarks',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
    ],
  },
];

const booleanStore = useBooleanStore();
// 创建一个响应式的本地副本
const localTableData = ref<any[]>([]);
const materialList = ref<any[]>([]);
// 数据库一共有多少条
const total = ref<number>(0);
const pageNum = ref<number>(1);
const pageSize = ref<number>(10);
const detailTotal = ref<number>(0);
const detailPageNum = ref<number>(1);
const detailPageSize = ref<number>(10);

async function getTableData(record: any) {
  try {
    const data = await getStocktakingDetail({
      planStocktakingId: record.id,
      current: detailPageNum.value,
      size: detailPageSize.value,
    });
    if (data.retCode === '200') {
      materialList.value = data.responseBody.records;
      detailTotal.value = data.responseBody?.total || 0;
    } else {
      Notification.error({
        title: '盘点明细查询失败',
        content: data.message,
        closable: true,
      });
    }
  } catch (error) {
    console.error('Error fetching stocktaking detail:', error);
    Notification.error({
      title: '错误',
      content: '获取盘点明细时发生错误',
      closable: true,
    });
  }
}

// 监听props.tableData的变化，并更新本地副本
watch(
  () => props.tableData,
  (newTableData) => {
    if (newTableData && newTableData.responseBody) {
      localTableData.value = newTableData.responseBody.records || [];
      total.value = newTableData.responseBody.total || 0;
      localTableData.value = localTableData.value.map((record) => {
        return {
          ...record,
          trayCodesArray: record.trayCode ? record.trayCode.split(',') : [],
        };
      });
    } else {
      localTableData.value = [];
      total.value = 0;
    }
    materialList.value = [];
  },
  { immediate: true }
);

function change(e: any) {
  pageNum.value = e;
}
function changeSize(e: any) {
  pageSize.value = e;
}
function detailChange(e: any) {
  detailPageNum.value = e;
}
function detailChangeSize(e: any) {
  detailPageSize.value = e;
}
function onEdit(record: any) {
  booleanStore.setRow(record);
  booleanStore.toggleBool(117);
}
// 删除
async function onDel(record: any) {
  const data = await getStocktakingDelete({
    id: record.id,
    user: getName() as string,
  });
  if (data.retCode === '200') {
    booleanStore.watchUpdate(115);
    Notification.success({
      title: '成功',
      content: data.message,
      closable: true,
    });
  } else {
    Notification.error({
      title: '失败',
      content: data.message,
      closable: true,
    });
  }
}
// 监听页面变化
watch([pageNum, pageSize], () => {
  booleanStore.setPage(pageNum.value, pageSize.value, 115);
});
</script>

<template>
  <div>
    <a-table
      :stripe="true"
      class="top-table"
      :pagination="false"
      :columns="columns"
      column-resizable
      :data="localTableData"
      @row-click="getTableData"
    >
      <template #index="{ record }">{{
        localTableData.indexOf(record) + 1
      }}</template>
      <template #type="{ record }">{{
        props.stocktakingTypeOptions.find((item) => item.value === record.type)
          ?.label
      }}</template>
      <template #status="{ record }">{{
        props.statusOptions.find((item) => item.value === record.status)?.label
      }}</template>
      <template #planDate="{ record }">{{
        dayjs(record.planDate).format('YYYY-MM-DD')
      }}</template>
      <template #finishedDate="{ record }">{{
        dayjs(record.finishedDate).format('YYYY-MM-DD')
      }}</template>
      <template #trayCode="{ record }">
        {{ record.trayCodesArray[0] }}
        <a-popover
          title="托盘信息"
          :content="record.trayCodesArray.join('\t')"
          v-if="record.trayCodesArray.length > 1"
        >
          <icon-more-vertical style="color: #696969" />
        </a-popover>
      </template>
      <template #materialCode="{ record }">
        {{ record.isLarge === 1 ? record.materials[0] : '' }}
        <a-popover
          title="物料信息"
          :content="record.materials.join('\t')"
          v-if="record.materials.length > 1 && record.isLarge === 1"
        >
          <icon-more-vertical style="color: #696969" />
        </a-popover>
      </template>
      <template #isLarge="{ record }">{{
        record.isLarge === 0 ? '否' : '是'
      }}</template>
      <template #action="{ record }">
        <a-button type="text" class="font-color" @click="onEdit(record)"
          >修改</a-button
        >
        <a-popconfirm
          content="确定删除吗?"
          ok-text="确认"
          cancel-text="取消"
          @ok="onDel(record)"
        >
          <a-button type="text" class="font-color">删除</a-button>
        </a-popconfirm>
      </template>
    </a-table>
    <div class="page-position">
      <a-pagination
        :total="total"
        :current="pageNum"
        :page-size="pageSize"
        show-total
        show-jumper
        show-page-size
        @change="change"
        @update:pageSize="changeSize"
      />
    </div>
    <a-table
      :stripe="true"
      class="top-table"
      :pagination="false"
      :columns="detailColumns"
      column-resizable
      :data="materialList"
      :scroll="{ y: 200 }"
      style="height: 250px; margin-top: 8px"
    >
      <template #index="{ record }">{{
        materialList.indexOf(record) + 1
      }}</template>
      <template #inventoryDate="{ record }">{{
        dayjs(record.inventoryDate).format('YYYY-MM-DD')
      }}</template>
    </a-table>
    <div class="page-position">
      <a-pagination
        :total="detailTotal"
        :current="detailPageNum"
        :page-size="detailPageSize"
        show-total
        show-jumper
        show-page-size
        @change="detailChange"
        @update:pageSize="detailChangeSize"
      />
    </div>
  </div>
</template>

<style scoped>
.top-table {
  white-space: nowrap;
}
.page-position {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
